package mm.chenchen.modules.mh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import mm.chenchen.constant.ResultMsg;

import mm.chenchen.db.annotation.DataSource;
import mm.chenchen.modules.mh.entity.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import mm.chenchen.utils.R;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import mm.chenchen.modules.mh.dao.MhRoleDao;
import mm.chenchen.utils.PageUtils;
import mm.chenchen.utils.PageModel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import mm.chenchen.modules.mh.dao.model.request.MhRoleQuery;
import org.springframework.util.ObjectUtils;


@Service("mhRoleService")
@Slf4j
@DataSource("mh_game_local")
public class MhRoleServiceImpl extends ServiceImpl<MhRoleDao, MhRole> {
    @Autowired
    private MhRaceBaseAttrServiceImpl raceBaseAttrService;
    @Autowired
    private MhBaseAttributeServiceImpl baseAttributeService;
    @Autowired
    private MhRoleAttrRelServiceImpl roleAttrRelService;
    @Autowired
    private MhDecorationsInfoServiceImpl decorationsInfoService;
    @Autowired
    private MhEquipmentInfoServiceImpl equipmentInfoService;

    public List<MhRole> getAll(){
        return list();
    }

    public R findPage(Page<Map> page, MhRoleQuery param) {
        Map<Long, MhBaseAttribute> baseAttrMap  = raceBaseAttrService.findByRace().stream().collect(Collectors.toMap(MhBaseAttribute::getId, Function.identity()));
        Map<Long,List<MhDecorationsInfo>> deMap=decorationsInfoService.list().stream().collect(Collectors.groupingBy(MhDecorationsInfo::getRoleId));
        Map<Long,List<MhEquipmentInfo>> eqMap=equipmentInfoService.list().stream().collect(Collectors.groupingBy(MhEquipmentInfo::getRoleId));
        Map<Long,MhBaseAttribute> disAttrMap=baseMapper.findDistribution("").stream().collect(Collectors.toMap(MhBaseAttribute::getRoleId,Function.identity()));


        IPage<MhRole> pageData = baseMapper.findPage(page, param);
        pageData.getRecords().forEach(e -> {
            listHandleDetail(e,baseAttrMap,deMap,eqMap,disAttrMap);
        });
        if (pageData != null) {
            return R.ok().setData(new PageModel(pageData.getRecords(), pageData.getTotal(), pageData.getSize(), pageData.getCurrent()));
        } else {
            return R.error(ResultMsg.DATA_NOT_EXIT);
        }
    }

    public R getById(Long id) {
        MhRole role = super.getById(id);
        handleDetail(role);
        return R.ok().setData(role);
    }

    public R saveInfo(MhRole param) {
        MhBaseAttribute distributeBaseAttr = param.getDistributeBaseAttr();
        baseAttributeService.save(distributeBaseAttr);
        super.save(param);
        MhRoleAttrRel roleAttrRel = new MhRoleAttrRel();
        roleAttrRel.setRoleId(param.getId());
        roleAttrRel.setBaseAttrId(distributeBaseAttr.getId());
        //分配类型
        roleAttrRel.setTypeId("1");
        roleAttrRelService.save(roleAttrRel);
        return R.ok();
    }

    public R update(MhRole param) {
        param.setUpdateTime(new Date());
        MhRole data = super.getById(param.getId());
        if (ObjectUtils.isEmpty(data)) {
            return R.error(ResultMsg.DATA_NOT_EXIT);
        }
        baseAttributeService.updateById(param.getDistributeBaseAttr());


        List<Long> eqIds = new ArrayList<>();
        eqIds.add(param.getZb().getXie());
        eqIds.add(param.getZb().getShi());
        eqIds.add(param.getZb().getTou());
        eqIds.add(param.getZb().getWu());
        eqIds.add(param.getZb().getYao());
        eqIds.add(param.getZb().getYi());
        UpdateWrapper<MhEquipmentInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(MhEquipmentInfo::getRoleId, param.getId()).in(MhEquipmentInfo::getId, eqIds);
        equipmentInfoService.update(updateWrapper);

        List<Long> deIds = new ArrayList<>();
        deIds.add(param.getLs().getErShi());
        deIds.add(param.getLs().getJieZhi());
        deIds.add(param.getLs().getPeiShi());
        deIds.add(param.getLs().getShouZhuo());
        UpdateWrapper<MhDecorationsInfo> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.lambda().set(MhDecorationsInfo::getRoleId, param.getId()).in(MhDecorationsInfo::getId, deIds);
        decorationsInfoService.update(updateWrapper1);

        return R.ok().setData(super.updateById(param));
    }

    public R deleteById(Long id) {
        return R.ok().setData(super.removeById(id));
    }

    public void listHandleDetail(MhRole role,Map<Long, MhBaseAttribute> baseAttrMap,Map<Long,List<MhDecorationsInfo>> deMap,Map<Long,List<MhEquipmentInfo>> eqMap,Map<Long,MhBaseAttribute> disAttrMap) {

        MhBaseAttribute eqBasAttr=new MhBaseAttribute();
        MhExpandAttribute eqExpAttr=new MhExpandAttribute();
        MhExpandAttribute deExpAttr=new MhExpandAttribute();

        QueryWrapper<MhDecorationsInfo> decorationsInfoQueryWrapper = new QueryWrapper<>();
        decorationsInfoQueryWrapper.lambda().eq(MhDecorationsInfo::getRoleId, role.getId());
        List<MhDecorationsInfo> deList = deMap.get(role.getId());
        if (deList!=null){
            deList.forEach(e -> {
                if (e.getType() == 1l) {
                    role.getLs().setJieZhi(e.getId());
                    role.getLs().setJieZhiDetail(e);
                } else if (e.getType() == 2l) {
                    role.getLs().setErShi(e.getId());
                    role.getLs().setErShiDetail(e);
                } else if (e.getType() == 3l) {
                    role.getLs().setShouZhuo(e.getId());
                    role.getLs().setShouZhuoDetail(e);

                } else if (e.getType() == 4l) {
                    role.getLs().setPeiShi(e.getId());
                    role.getLs().setPeiShiDetail(e);
                }
            });
        }


        QueryWrapper<MhEquipmentInfo> equipmentInfoQueryWrapper = new QueryWrapper<>();
        equipmentInfoQueryWrapper.lambda().eq(MhEquipmentInfo::getRoleId, role.getId());
        List<MhEquipmentInfo> zbList = eqMap.get(role.getId());
        if (!ObjectUtils.isEmpty(zbList)){
            zbList.forEach(e -> {
                equipmentInfoService.handleDetail(e);
                eqExpAttr.add(e.getExpandAttr());
                eqBasAttr.add(e.getBaseAttr());
                if (e.getType() == 1l) {
                    role.getZb().setWu(e.getId());
                    role.getZb().setWuDetail(e);
                } else if (e.getType() == 2l || e.getType() == 7) {
                    role.getZb().setTou(e.getId());
                    role.getZb().setTouDetail(e);
                } else if (e.getType() == 3l || e.getType() == 8) {
                    role.getZb().setYi(e.getId());
                    role.getZb().setYiDetail(e);
                } else if (e.getType() == 4l) {
                    role.getZb().setShi(e.getId());
                    role.getZb().setShiDetail(e);
                } else if (e.getType() == 5l) {
                    role.getZb().setYao(e.getId());
                    role.getZb().setYaoDetail(e);
                } else if (e.getType() == 6l) {
                    role.getZb().setXie(e.getId());
                    role.getZb().setXieDetail(e);
                }
            });
        }


        role.setRaceBaseAttr(baseAttrMap.get(Long.parseLong(role.getRace() + "")).clone());

        role.getRaceBaseAttr().addLevelAttr(role.getLevel());

        role.setDistributeBaseAttr(disAttrMap.get(role.getId()));

        role.getDistributeBaseAttr().handleTotal();
        role.setAttrProportion(role.getDistributeBaseAttr().getProportion());


        role.setEquipmentBaseAttr(eqBasAttr);

        role.getTotalBaseAttr().add(role.getRaceBaseAttr());
        role.getTotalBaseAttr().add(role.getDistributeBaseAttr());
        role.getTotalBaseAttr().add(role.getEquipmentBaseAttr());
        role.getTotalBaseAttr().add(role.getOtherBaseAttr());

        role.setAttrLevelExpandAttribute(handleExpandAttr(role.getRace(), role.getRaceBaseAttr()));
        role.setAttrDistributeExpandAttribute(handleExpandAttr(role.getRace(), role.getDistributeBaseAttr()));

        role.getTotalExpandAttr().add(role.getBaseExpandAttribute());
        role.getTotalExpandAttr().add(role.getAttrLevelExpandAttribute());
        role.getTotalExpandAttr().add(role.getAttrDistributeExpandAttribute());
        role.getTotalExpandAttr().add(role.getEquipmentExpandAttribute());
        role.getTotalExpandAttr().add(role.getDecorationsExpandAttribute());

        role.getTotalExpandAttr().setBlood(new BigDecimal(role.getTotalExpandAttr().getBlood()).multiply(new BigDecimal(role.getXueSkill()).divide(new BigDecimal(100))).add(new BigDecimal(role.getTotalExpandAttr().getBlood())).doubleValue());
        role.getTotalExpandAttr().setMagic(new BigDecimal(role.getTotalExpandAttr().getMagic()).multiply(new BigDecimal(role.getLanSkill()).divide(new BigDecimal(100))).add(new BigDecimal(role.getTotalExpandAttr().getMagic())).doubleValue());
    }


    public void handleDetail(MhRole role) {
        MhBaseAttribute eqBasAttr=new MhBaseAttribute();
        MhExpandAttribute eqExpAttr=new MhExpandAttribute();
        MhExpandAttribute deExpAttr=new MhExpandAttribute();
        QueryWrapper<MhDecorationsInfo> decorationsInfoQueryWrapper = new QueryWrapper<>();
        decorationsInfoQueryWrapper.lambda().eq(MhDecorationsInfo::getRoleId, role.getId());
        List<MhDecorationsInfo> deList = decorationsInfoService.list(decorationsInfoQueryWrapper);
        deList.forEach(e -> {
            if (e.getType() == 1l) {
                role.getLs().setJieZhi(e.getId());
                role.getLs().setJieZhiDetail(e);
            } else if (e.getType() == 2l) {
                role.getLs().setErShi(e.getId());
                role.getLs().setErShiDetail(e);
            } else if (e.getType() == 3l) {
                role.getLs().setShouZhuo(e.getId());
                role.getLs().setShouZhuoDetail(e);

            } else if (e.getType() == 4l) {
                role.getLs().setPeiShi(e.getId());
                role.getLs().setPeiShiDetail(e);
            }
        });

        QueryWrapper<MhEquipmentInfo> equipmentInfoQueryWrapper = new QueryWrapper<>();
        equipmentInfoQueryWrapper.lambda().eq(MhEquipmentInfo::getRoleId, role.getId());
        List<MhEquipmentInfo> zbList = equipmentInfoService.list(equipmentInfoQueryWrapper);
        zbList.forEach(e -> {
            equipmentInfoService.handleDetail(e);
            eqExpAttr.add(e.getExpandAttr());
            eqBasAttr.add(e.getBaseAttr());
            if (e.getType() == 1l) {
                role.getZb().setWu(e.getId());
                role.getZb().setWuDetail(e);
            } else if (e.getType() == 2l || e.getType() == 7) {
                role.getZb().setTou(e.getId());
                role.getZb().setTouDetail(e);
            } else if (e.getType() == 3l || e.getType() == 8) {
                role.getZb().setYi(e.getId());
                role.getZb().setYiDetail(e);
            } else if (e.getType() == 4l) {
                role.getZb().setShi(e.getId());
                role.getZb().setShiDetail(e);
            } else if (e.getType() == 5l) {
                role.getZb().setYao(e.getId());
                role.getZb().setYaoDetail(e);
            } else if (e.getType() == 6l) {
                role.getZb().setXie(e.getId());
                role.getZb().setXieDetail(e);
            }

        });

        Map<Long, MhBaseAttribute> map = raceBaseAttrService.findByRace().stream().collect(Collectors.toMap(MhBaseAttribute::getId, Function.identity()));
        role.setRaceBaseAttr(map.get(Long.parseLong(role.getRace() + "")));
        role.getRaceBaseAttr().addLevelAttr(role.getLevel());
        role.setDistributeBaseAttr(baseMapper.findDistribution(role.getId() + "").get(0));
        role.getDistributeBaseAttr().handleTotal();
        role.setAttrProportion(role.getDistributeBaseAttr().getProportion());


        role.setEquipmentBaseAttr(eqBasAttr);

        role.getTotalBaseAttr().add(role.getRaceBaseAttr());
        role.getTotalBaseAttr().add(role.getDistributeBaseAttr());
        role.getTotalBaseAttr().add(role.getEquipmentBaseAttr());
        role.getTotalBaseAttr().add(role.getOtherBaseAttr());

        role.setAttrLevelExpandAttribute(handleExpandAttr(role.getRace(), role.getRaceBaseAttr()));
        role.setAttrDistributeExpandAttribute(handleExpandAttr(role.getRace(), role.getDistributeBaseAttr()));

        role.getTotalExpandAttr().add(role.getBaseExpandAttribute());
        role.getTotalExpandAttr().add(role.getAttrLevelExpandAttribute());
        role.getTotalExpandAttr().add(role.getAttrDistributeExpandAttribute());
        role.getTotalExpandAttr().add(role.getEquipmentExpandAttribute());
        role.getTotalExpandAttr().add(role.getDecorationsExpandAttribute());

        role.getTotalExpandAttr().setBlood(new BigDecimal(role.getTotalExpandAttr().getBlood()).multiply(new BigDecimal(role.getXueSkill()).divide(new BigDecimal(100))).add(new BigDecimal(role.getTotalExpandAttr().getBlood())).doubleValue());
        role.getTotalExpandAttr().setMagic(new BigDecimal(role.getTotalExpandAttr().getMagic()).multiply(new BigDecimal(role.getLanSkill()).divide(new BigDecimal(100))).add(new BigDecimal(role.getTotalExpandAttr().getMagic())).doubleValue());
    }

    private MhExpandAttribute handleExpandAttr(int raceId, MhBaseAttribute baseAttribute) {

        MhExpandAttribute expandAttribute = new MhExpandAttribute();

        if (mm.chenchen.utils.ObjectUtils.isEmpty(baseAttribute)) {
            return expandAttribute;
        }

        MhExpandAttribute li = MhExpandAttribute.handleByBaseAttr(raceId, 1);
        li.handleWithBaseCount(baseAttribute.getLi());
        MhExpandAttribute mo = MhExpandAttribute.handleByBaseAttr(raceId, 2);
        mo.handleWithBaseCount(baseAttribute.getMo());
        MhExpandAttribute ti = MhExpandAttribute.handleByBaseAttr(raceId, 3);
        ti.handleWithBaseCount(baseAttribute.getTi());
        MhExpandAttribute nai = MhExpandAttribute.handleByBaseAttr(raceId, 4);
        nai.handleWithBaseCount(baseAttribute.getNai());
        MhExpandAttribute min = MhExpandAttribute.handleByBaseAttr(raceId, 5);
        min.handleWithBaseCount(baseAttribute.getMin());

        expandAttribute.add(li);
        expandAttribute.add(mo);
        expandAttribute.add(ti);
        expandAttribute.add(min);
        expandAttribute.add(nai);

        return expandAttribute;
    }

}